package com.zyguo.sdk.common;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import com.zyguo.sdk.thread.BLThreadPool;

public class AbstractTask<T extends Object> {
	private BLThreadPool threadPool = new BLThreadPool();
	public static final int DEFAULT_MAX_WAIT_SEC = 10;
	
	/**
	 * 异步执行某个任务
	 */
	protected boolean asynDoTask( Runnable runnable ){
		threadPool.submit( runnable );
		return true;
	}
	
	/**
	 * 同步执行某个任务
	 * @param callable
	 * @param maxWaitSec
	 * @return
	 * @throws Exception
	 */
	protected T syncDoTask( Callable<T> callable, int maxWaitSec ) throws Exception{
		Future<T> future = threadPool.submit( callable );
		
		if( maxWaitSec <=0 || maxWaitSec > DEFAULT_MAX_WAIT_SEC ){
			maxWaitSec = DEFAULT_MAX_WAIT_SEC;
		}
		
		try {
			T result = future.get( maxWaitSec, TimeUnit.SECONDS );
			return result;
		} catch (Exception e) {
			throw e;
		} 
	}

	public void setThreadPool(BLThreadPool threadPool) {
		this.threadPool = threadPool;
	} 
}
